import pymongo
import re


class SearchSpinder():
    def __init__(self,keyword,pagesize,pagenum):
        self.myclient = pymongo.MongoClient("mongodb://139.155.1.113:27017")
        self.mydb = self.myclient["QK_GOODS"]
        self.mycol = self.mydb["goods"]
        self.keyword = keyword
        self.pagesize = int(pagesize)
        self.pagenum = int(pagenum)

    def search_goods(self):
        mongodata = self.mycol.find({'itemName':re.compile(self.keyword)}).limit(self.pagesize).skip(self.pagesize*self.pagenum).sort("updateTime",pymongo.DESCENDING)
        total = self.mycol.find({'itemName':re.compile(self.keyword)}).count()
        result = []
        for one in mongodata:
            one.pop('_id')
            result.append(one)

        return total,result


def spider(keyword,pagesize,pagenum):

    try:
        pagesize = int(pagesize)
    except:
        pagesize = -1
    try:
        pagenum = int(pagenum)
    except:
        pagenum = -1

    search = SearchSpinder(keyword,pagesize,pagenum)
    try:
        total,result = search.search_goods()
    except:
        total, result = 0,[]
    try:
        total_page = total//pagesize
    except:
        total_page = 0

    res = {}
    res['keyword'] = keyword
    res['totalpage'] = total_page
    res['pagesize'] = pagesize
    res['currentpage'] = pagenum
    res['data'] = result
    res['code'] = 'success'
    if result == []:
        res['code'] = 'erro'

    return res
